<!-- 专业洗车页面 -->
<template>
  <view class="wash">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <uni-search-bar
        placeholder="搜索"
        class="search-bar-input"
        clearButton="auto"
        cancelButton="none"
        @confirm="search"
        :focus="true"
        v-model="searchValue">
      </uni-search-bar>

      <view class="search-btn" @click="search">搜索</view>
    </view>

    <!-- 中间内容区域 -->
    <scroll-view
      class="scroll-view"
      refresher-background="#E3E1F0"
      :show-scrollbar="false"
      :refresher-enabled="true"
      :refresher-triggered="isTriggerRefresher"
      @scrolltolower="onReachBottom"
      @refresherrefresh="onPullDownRefresh"
      scroll-y>
      <!-- 点击图片跳转页面 -->
      <navigator
        hover-class="navigator-hover"
        v-for="item in scrollData"
        :key="item.id"
        :url="`/pages/WashCar/index?id=${item.id}`">
        <view class="scroll-view-item">
          <!-- 左边图片部分 -->
          <view class="left-img">
            <image
              :src="item.imgs[0]"
              class="scroll-view-item-image"
              mode="widthFix" />
          </view>

          <!-- 右边内容区域 -->
          <view class="right-content">
            <!-- 店铺名称 & 距离 -->
            <view class="row-one">
              <view class="name">{{ item.name }}</view>
              <view class="distance">{{ item.distance }}m</view>
            </view>
            <!-- 评价 & 销量 -->
            <view class="row-two">
              <!-- 星级 -->
              <view class="star">
                <view class="white-star">
                  <!-- 根据分数百分比指定橙色星星的宽度 满分5分 -->
                  <view
                    class="orange-star"
                    :style="{ width: `${item.rate * 20}%` }"></view>
                </view>
              </view>
              <view class="evaluation">{{ item.rate }}分</view>
              <view class="sales">销量: {{ item.sales }}</view>
            </view>
            <!-- 营业时间 -->
            <view class="row-three">
              营业时间: 工作日{{ item.businessTime }}
            </view>
            <!-- 地址 -->
            <view class="row-four">
              {{ item.address }}
            </view>
          </view>
        </view>
      </navigator>

      <!-- 加载更多 -->
      <view class="load-more">
        {{ moreData[finish] }}
      </view>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { getMerchantListApi } from "@/api/WashCarApi";
//导入useMerchantStore 函数 用来持久化存储商户数据
import { useMerchantStore } from "@/stores/merchantInfo";

/** ------start 顶部搜索栏功能 ------------------ */
//搜索栏绑定值
const searchValue = ref("");
//搜索框的确认事件 当用户按下回车触发后者点击那个搜索图标触发
const search = () => {
  //对用户是否输入进行判断
  if (!searchCheck()) {
    return;
  }

  //TODO 调用后端接口 获取搜索结果，下面searchBtn函数也需要调用同样接口

  console.log(searchValue.value);
};
//用户点击搜索事件触发搜索
const searchBtn = () => {
  //对用户是否输入进行判断
  if (!searchCheck()) {
    return;
  }

  console.log(searchValue.value);
};
//判断函数 当用户输入框中有值时才触发搜索，无值时搜索进行提示
const searchCheck = () => {
  if (searchValue.value.trim() === "") {
    uni.showToast({
      title: "请输入搜索内容",
      icon: "none",
      duration: 2000,
    });
    return false;
  }

  return true;
};

/** ------end 顶部搜索栏功能 ------------------ */

//=========数据定义区域=====================
//下拉刷新触发属性 默认为false 不刷新
const isTriggerRefresher = ref(false);
//底部加载更多判断属性 值0表示刚开始不显示加载更多  1表示还有数据显示加载更多
//2.表示没有更多数据了
const finish = ref(0);
//页末显示更多数据的数组
const moreData = ref(["", "加载更多...", "没有更多了~"]);

//内容展示数据
const scrollData = ref<MerchantListResponse[]>([]);
//定义请求头参数
const requestParams = ref({
  pageNum: 1,
  pageSize: 5,
  latitude: null as number | null, //定义纬度
  longitude: null as number | null, //定义经度
});
//记录总的页数
const totalPages = ref(-1);
//记录当前页数
const currentPage = ref(-1);

//==============   中间核心函数区域  =====================
//1 发请求 获取数据函数
const getMerchantList = async () => {
  //1.1 获取位置信息 经纬度 这里等待加载完经纬度再往下执行
  const locationRes = await uni.getLocation({
    type: "wgs84",
  });
  console.log("获取到的经纬度是：", locationRes);
  //将获取到的经纬度赋值给请求头参数
  requestParams.value.latitude = locationRes.latitude;
  requestParams.value.longitude = locationRes.longitude;

  //1.2 开启加载框
  uni.showLoading({
    title: "加载中...",
    mask: true,
  });

  //1.3. 像后端发请求 获取数据
  getMerchantListApi(requestParams.value)
    .then((res) => {
      console.log(res);
      //合并原来的数据
      scrollData.value = [...scrollData.value, ...res.data.list];
      //记录当前页数和总页数
      currentPage.value = res.data.pageNum;
      totalPages.value = res.data.pages;
      //判断是否是最后一页
      isLastPage();

      //2.3. 持久化存储数据 便于洗车页面获取数据
      const merchantStore = useMerchantStore();
      merchantStore.merchantInfoList = scrollData.value;
      console.log("持久化存储数据：", merchantStore.merchantInfoList);

      //2.4 页面加载完毕后 关闭下拉刷新 & 隐藏加载中
      uni.hideLoading();
    })
    .catch((err) => {
      console.log(err);
      uni.hideLoading();
    });
};

//2.下拉刷新 从第一页开始加载数据
const onPullDownRefresh = async () => {
  //2.1 开启下拉刷新
  isTriggerRefresher.value = true;

  //2.2 像后端发请求 获取数据
  //修改分页参数
  requestParams.value.pageNum = 1;
  requestParams.value.pageSize = 5;
  //清空原数据
  scrollData.value = [];
  //重新加载数据 加载完数据后关闭下拉刷新
  await getMerchantList();

  //2.3. 页面加载完毕 关闭下拉刷新
  isTriggerRefresher.value = false;
};

//3. 上滑加载更多
const onReachBottom = async () => {
  //3.1. 判断是否是最后一页
  if (currentPage.value === totalPages.value && totalPages.value !== -1) {
    //说明已经是最后一页了
    finish.value = 2;
    uni.showToast({
      title: "没有更多了~",
      icon: "none",
      duration: 2000,
    });
    return;
  }

  //3.2 不是最后一页 继续加载数据
  //修改分页参数
  requestParams.value.pageNum = currentPage.value + 1;
  requestParams.value.pageSize = 3;

  //加载数据
  await getMerchantList();
};

//判断函数 用来判断当前是否是最后一页
const isLastPage = () => {
  if (currentPage.value === -1 && totalPages.value === -1) {
    //说明是刚加载页面
    finish.value = 0;
    return;
  }
  if (currentPage.value + 1 > totalPages.value) {
    //说明已经是最后一页了
    finish.value = 2;
  } else {
    //说明还有数据
    finish.value = 1;
  }
};
//进入页面时初始化调用数据
onMounted(() => {
  getMerchantList();
  console.log("页面加载了...");
});
</script>

<style scoped lang="scss">
.wash {
  background-color: #efefef;
  box-sizing: border-box;
  height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;

  /**搜索栏样式 */
  .search-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background-color: #fff;

    .search-bar-input {
      flex: 1;
    }

    .search-btn {
      width: 80rpx;
    }
  }

  /**中间内容区域样式 */
  .scroll-view {
    display: flex;
    flex-direction: column;
    background-color: #e3e1f0;
    flex: 1;
    padding-top: 120rpx; /*为固定定位的搜索栏预留空间 */
    height: 0; /* 配合flex:1使用，确保scroll-view可以正确计算高度 */
    padding-bottom: env(safe-area-inset-bottom);
    padding-bottom: constant(safe-area-inset-bottom);

    .scroll-view-item {
      width: 100%;
      height: 300rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      padding: 20rpx;
      margin-bottom: 20rpx;
      border-bottom: 1rpx solid #222436;
      gap: 20rpx;

      .left-img {
        width: 35%;
        height: 280rpx;
        overflow: hidden;
        image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .right-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        gap: 20rpx;

        .row-one {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .name {
            font-size: 32rpx;
            font-weight: bold;
          }
          .distance {
            font-size: 28rpx;
            color: #87ceeb;
          }
        }

        .row-two {
          display: flex;
          justify-self: space-between;
          align-items: center;
          gap: 20rpx;

          .star {
            width: 118rpx;
            height: 25rpx;
            .white-star {
              width: 100%;
              height: 100%;
              background-image: url("https://bucket-yueyang.oss-cn-shanghai.aliyuncs.com/star-white.png");
            }
            .orange-star {
              width: 0;
              height: 100%;
              background-image: url("https://bucket-yueyang.oss-cn-shanghai.aliyuncs.com/star-orange.png");
            }
          }

          .evaluation {
            color: gainsboro;
          }
        }
      }
    }

    .load-more {
      text-align: center;
      font-size: 28rpx;
      color: #000;
      padding: 10rpx 0;
    }
  }
}
</style>
